package info.batcloud.fanli.core.item.collection;

import com.ctospace.archit.common.pagination.Paging;
import info.batcloud.fanli.core.dto.CommissionItemFetchDTO;
import info.batcloud.fanli.core.entity.ItemSelection;
import info.batcloud.fanli.core.enums.ItemSelectionType;
import info.batcloud.fanli.core.repository.ItemSelectionRepository;
import info.batcloud.fanli.core.service.CommissionItemService;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.settings.ItemSelectionSetting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class ItemSelectionCollectorDispatcher extends AbstractItemSelectionCollector<ItemSelectionContext> {

    private static final Logger logger = LoggerFactory.getLogger(CommissionItemCollector.class);

    @Inject
    private CommissionItemService commissionItemService;

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private ItemSelectionRepository itemSelectionRepository;

    @Override
    public CollectResult collect(ItemSelectionContext context, Consumer<Paging<CommissionItemFetchDTO>> pagingConsumer) {
        final ItemSelectionSetting itemSelectionSetting = systemSettingService.findActiveSetting(ItemSelectionSetting.class);
        ItemSelection itemSelection = itemSelectionRepository.findOne(context.getItemSelectionId());
        AbstractItemSelectionCollector commissionItemCollector = COLLECTOR_MAP.get(itemSelection.getType());
        CollectResult result = commissionItemCollector.collect(context.getItemSelectionId(), new Consumer<Paging<CommissionItemFetchDTO>>() {
            @Override
            public void accept(Paging<CommissionItemFetchDTO> fetchBOPaging) {
                List<CommissionItemFetchDTO> list = fetchBOPaging.getResults().stream().filter(item -> item.getSales() >= itemSelectionSetting
                        .getMinSales()).collect(Collectors.toList());
                commissionItemService.saveCommissionItemListSync(list);
            }
        });
        return result;
    }

    @Override
    public CollectResult collect(long itemSelectionId, Consumer<Paging<CommissionItemFetchDTO>> pagingConsumer) {
        ItemSelectionContext context = new ItemSelectionContext();
        context.setItemSelectionId(itemSelectionId);
        return collect(context, pagingConsumer);
    }

    @Override
    public Class<ItemSelectionContext> getContextType() {
        return ItemSelectionContext.class;
    }

    @Override
    protected ItemSelectionType getItemSelectionType() {
        return null;
    }
}
